<template>
  <div class="quick-upload-container">
    <!-- 收缩状态的小窗口 -->
    <div
      v-if="!isExpanded"
      class="collapsed-window"
      :class="{ 'compact-mode': compactMode, 'icon-only': iconOnly }"
      :title="iconOnly ? '点击上传文件' : ''"
      @click="toggleExpand"
    >
      <div class="collapsed-content">
        <i class="el-icon-upload2" />
        <span v-if="!compactMode && !iconOnly" class="collapsed-text">快速上传</span>
        <span v-if="compactMode && !iconOnly" class="collapsed-text">上传</span>
        <i v-if="!iconOnly" class="el-icon-arrow-down expand-icon" />
      </div>
    </div>

    <!-- 展开状态的完整上传界面 -->
    <div v-if="isExpanded" class="expanded-window" :class="{ 'default-expanded': defaultExpanded }">
      <!-- 收缩提示条 -->
      <div v-if="!defaultExpanded" class="collapse-hint" @click="toggleExpand">
        <i class="el-icon-arrow-up" />
        <span>收起</span>
      </div>

      <div class="upload-content">
        <div class="upload-layout">
          <!-- 左侧上传区域 -->
          <div class="upload-left">
            <el-tabs v-model="uploadType" class="upload-tabs" size="small">
              <el-tab-pane label="本地文件" name="local">
                <el-upload
                  ref="upload"
                  :headers="headers"
                  :action="upload_url"
                  :multiple="true"
                  drag
                  :auto-upload="true"
                  :file-list="fileList"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :data="uploadData"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :on-progress="handleProgress"
                  :on-error="handleError"
                  :class="{ 'uploading': isUploading || isFolderUploading }"
                  class="upload-area"
                  @drop.native="handleCustomDrop"
                  @dragover.native="handleCustomDragOver"
                >
                  <div v-if="!isUploading && !isFolderUploading" class="upload-normal">
                    <i class="el-icon-upload" />
                    <div class="el-upload__text">拖拽文件或<em>点击上传</em></div>
                    <div class="el-upload__tip">支持单文件、多文件和文件夹上传</div>
                  </div>
                  <div v-else-if="isUploading && !isFolderUploading" class="upload-progress">
                    <i class="el-icon-loading uploading-icon" />
                    <div class="uploading-text">正在上传文件...</div>
                    <div v-if="uploadingFiles > 0" class="uploading-count">
                      {{ uploadingFiles }} 个文件上传中
                    </div>
                  </div>
                  <div v-else-if="isFolderUploading" class="folder-upload-progress">
                    <i class="el-icon-folder" />
                    <div class="folder-upload-text">
                      正在上传文件夹: {{ currentFolderUpload.folderName }}
                    </div>
                    <div class="folder-upload-count">
                      {{ currentFolderUpload.uploadedFiles }} / {{ currentFolderUpload.totalFiles }}
                    </div>
                    <el-progress
                      :percentage="folderUploadPercentage"
                      :show-text="false"
                      style="margin-top: 5px; width: 100%;"
                    />
                  </div>
                </el-upload>
              </el-tab-pane>

              <el-tab-pane label="粘贴图片" name="paste">
                <div class="paste-tab-content">
                  <div
                    ref="pasteArea"
                    class="paste-area"
                    :class="{ 'uploading': isPasteUploading }"
                    contenteditable="true"
                    placeholder="在此处粘贴图片"
                    @paste="handlePaste"
                  >
                    <div v-if="!isPasteUploading" class="paste-hint">
                      <i class="el-icon-picture-outline" />
                      <p>粘贴图片到此处</p>
                      <p class="paste-tip">使用 Ctrl+V 或 Cmd+V 粘贴</p>
                      <p class="paste-tip">粘贴后会自动上传</p>
                    </div>
                    <div v-else class="paste-uploading">
                      <i class="el-icon-loading" />
                      <p>正在上传图片...</p>
                    </div>
                  </div>

                  <!-- 访问权限配置 -->
                  <div class="paste-options">
                    <el-select
                      v-model="acl_type"
                      size="mini"
                      class="access-select"
                      placeholder="权限"
                    >
                      <el-option label="7天" value="7" />
                      <el-option label="3天" value="3" />
                      <el-option label="公开" value="public_read" />
                    </el-select>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>

          <!-- 右侧成功列表 -->
          <div v-if="success_data.length" class="upload-right">
            <div class="success-header">
              <span class="success-title">
                <i class="el-icon-check" />
                已上传 ({{ success_data.length }})
              </span>
              <el-button type="text" size="mini" class="clear-btn" @click="clearResults">
                <i class="el-icon-delete" />
              </el-button>
            </div>
            <div class="success-list">
              <div v-for="(item,index) in success_data.slice(-5)" :key="index" class="success-item">
                <i class="el-icon-document" />
                <el-link :href="item.url" target="_blank" class="file-name">
                  {{ item.filename }}
                </el-link>
                <el-tag type="success" size="mini" class="success-tag">
                  <i class="el-icon-check" />
                </el-tag>
              </div>
              <div v-if="success_data.length > 5" class="more-files">
                还有 {{ success_data.length - 5 }} 个文件...
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 文件夹上传确认对话框 -->
    <el-dialog
      title="确认上传文件夹"
      :visible.sync="folderUploadConfirm.visible"
      append-to-body
      width="400px"
    >
      <div class="folder-confirm-content">
        <p>检测到文件夹: <strong>{{ folderUploadConfirm.folderName }}</strong></p>
        <p>包含 <strong>{{ folderUploadConfirm.fileCount }}</strong> 个文件</p>
        <p class="folder-tag-hint">
          所有文件将使用 "{{ folderUploadConfirm.folderName }}" 作为文件夹标签
        </p>
      </div>
      <div slot="footer">
        <el-button @click="folderUploadConfirm.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmFolderUpload">确认上传</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'Crmfilequickuploader',

  props: {
    // 默认目录名称
    defaultDirectory: {
      type: String,
      default: 'default'
    },
    // 默认访问权限
    defaultAcl: {
      type: String,
      default: 'public_read'
    },
    // 默认目录ID（如果有的话）
    defaultDirectoryId: {
      type: [String, Number],
      default: null
    },
    // 目录名称
    directoryName: {
      type: String,
      default: ''
      // 传递给后端API的目录名称，用于指定文件上传到哪个目录
    },
    // 默认展开状态
    defaultExpanded: {
      type: Boolean,
      default: false
      // 控制组件是否默认展开，true为展开，false为收起
    },
    // 紧凑模式
    compactMode: {
      type: Boolean,
      default: false
      // 控制是否启用紧凑模式，true为紧凑显示，false为正常显示
    },
    // 仅图标模式
    iconOnly: {
      type: Boolean,
      default: false
      // 控制是否只显示图标，true为只显示图标，false为显示文字
    }
  },

  data() {
    return {
      // 展开/收缩状态
      isExpanded: this.defaultExpanded,
      // 上传相关
      uploadType: 'local',
      fileList: [],
      upload_url: '',
      pastedImage: '',
      pastedImageType: 'image/png',
      success_data: [],
      listObj: {},
      acl_type: this.defaultAcl,
      isUploading: false,
      uploadingFiles: 0,
      // 粘贴图片上传状态
      isPasteUploading: false,
      // 文件夹上传相关
      isFolderUploading: false,
      currentFolderUpload: null,
      folderUploadConfirm: {
        visible: false,
        folderName: '',
        fileList: [],
        fileCount: 0
      }
    }
  },

  computed: {
    headers() {
      return {
        'Authorization': getToken()
      }
    },

    // 上传数据
    uploadData() {
      return {
        directory_id: this.defaultDirectoryId || -1,
        acl_type: this.acl_type,
        project_id: this.$store.getters.projectId,
        directory_name: this.directoryName
      }
    },

    // 文件夹上传进度百分比
    folderUploadPercentage() {
      if (!this.currentFolderUpload || this.currentFolderUpload.totalFiles === 0) {
        return 0
      }
      return Math.round((this.currentFolderUpload.uploadedFiles / this.currentFolderUpload.totalFiles) * 100)
    }
  },

  mounted() {
    this.upload_url = process.env.VUE_APP_BASE_API + '/crm/api/crmfile/'
  },

  methods: {
    // 切换展开/收缩状态
    toggleExpand() {
      this.isExpanded = !this.isExpanded
    },

    // 自定义拖拽事件处理
    handleCustomDragOver(event) {
      event.preventDefault()
      event.stopPropagation()
    },

    // 自定义拖拽放置事件处理
    async handleCustomDrop(event) {
      event.preventDefault()
      event.stopPropagation()

      const items = event.dataTransfer.items
      let hasFolder = false

      // 检查是否包含文件夹
      for (let i = 0; i < items.length; i++) {
        const item = items[i]
        if (item.webkitGetAsEntry && item.webkitGetAsEntry().isDirectory) {
          hasFolder = true
          break
        }
      }

      if (hasFolder) {
        // 包含文件夹，使用自定义处理
        await this.processFolderDrop(items)
      } else {
        // 不包含文件夹，让el-upload组件处理
        // 这里不需要特殊处理，让默认的上传逻辑处理
      }
    },

    // 处理文件夹拖拽
    async processFolderDrop(items) {
      for (let i = 0; i < items.length; i++) {
        const item = items[i]
        const entry = item.webkitGetAsEntry()

        if (entry && entry.isDirectory) {
          // 找到文件夹，开始处理
          await this.processFolderUpload(entry)
          return // 只处理第一个文件夹
        }
      }
    },

    // 处理文件夹上传
    async processFolderUpload(folderEntry) {
      const folderName = folderEntry.name || '默认'
      const allFiles = []

      try {
        // 递归遍历文件夹
        await this.traverseFolder(folderEntry, allFiles, folderName)

        if (allFiles.length === 0) {
          this.$message.warning('文件夹中没有找到任何文件')
          return
        }

        // 显示确认对话框
        this.showFolderUploadConfirm(folderName, allFiles)
      } catch (error) {
        console.error('处理文件夹失败:', error)
        this.$message.error('读取文件夹失败，请重试')
      }
    },

    // 递归遍历文件夹
    async traverseFolder(entry, fileList, folderTag, relativePath = '') {
      if (entry.isFile) {
        // 是文件，添加到列表
        const file = await this.getFileFromEntry(entry)
        fileList.push({
          file: file,
          relativePath: relativePath + file.name,
          folderTag: folderTag
        })
      } else if (entry.isDirectory) {
        // 是目录，继续遍历
        const reader = entry.createReader()
        const entries = await this.readAllEntries(reader)

        for (const childEntry of entries) {
          await this.traverseFolder(
            childEntry,
            fileList,
            folderTag,
            relativePath + entry.name + '/'
          )
        }
      }
    },

    // 从Entry获取File对象
    getFileFromEntry(entry) {
      return new Promise((resolve, reject) => {
        entry.file(resolve, reject)
      })
    },

    // 读取目录中的所有条目
    readAllEntries(reader) {
      return new Promise((resolve, reject) => {
        const allEntries = []

        const readEntries = () => {
          reader.readEntries((entries) => {
            if (entries.length === 0) {
              // 没有更多条目了
              resolve(allEntries)
            } else {
              // 还有更多条目，继续读取
              allEntries.push(...entries)
              readEntries()
            }
          }, reject)
        }

        readEntries()
      })
    },

    // 显示文件夹上传确认对话框
    showFolderUploadConfirm(folderName, fileList) {
      this.folderUploadConfirm = {
        visible: true,
        folderName: folderName,
        fileList: fileList,
        fileCount: fileList.length
      }
    },

    // 确认上传文件夹
    async confirmFolderUpload() {
      const { folderName, fileList } = this.folderUploadConfirm

      this.folderUploadConfirm.visible = false
      await this.uploadFolderFiles(folderName, fileList)
    },

    // 批量上传文件夹中的文件
    async uploadFolderFiles(folderName, fileList) {
      this.currentFolderUpload = {
        folderName: folderName,
        totalFiles: fileList.length,
        uploadedFiles: 0,
        successFiles: [],
        failedFiles: []
      }

      // 显示文件夹上传进度
      this.isFolderUploading = true

      try {
        // 逐个上传文件
        for (const fileItem of fileList) {
          try {
            const result = await this.uploadSingleFileWithFolderTag(fileItem)
            this.currentFolderUpload.successFiles.push(result)
            this.$notify({
              title: '文件上传成功',
              message: `${fileItem.file.name} 上传成功`,
              type: 'success',
              duration: 1500
            })
          } catch (error) {
            this.currentFolderUpload.failedFiles.push({
              ...fileItem,
              error: error
            })
            this.$notify({
              title: '文件上传失败',
              message: `${fileItem.file.name} 上传失败: ${error.message || '未知错误'}`,
              type: 'error',
              duration: 3000
            })
          }

          this.currentFolderUpload.uploadedFiles++
        }

        // 上传完成，返回结果给父组件
        this.emitFolderUploadComplete()
      } catch (error) {
        console.error('文件夹上传失败:', error)
        this.$message.error('文件夹上传失败，请重试')
        this.isFolderUploading = false
        this.currentFolderUpload = null
      }
    },

    // 上传单个文件（带文件夹标签）
    async uploadSingleFileWithFolderTag(fileItem) {
      // 构造上传数据，包含folder_tag
      const uploadData = {
        directory_id: this.defaultDirectoryId || -1,
        acl_type: this.acl_type,
        project_id: this.$store.getters.projectId,
        directory_name: this.directoryName,
        folder_tag: fileItem.folderTag
      }

      // 使用FormData上传
      const formData = new FormData()
      formData.append('file', fileItem.file)
      Object.keys(uploadData).forEach(key => {
        formData.append(key, uploadData[key])
      })

      const response = await this.uploadFileRequest(formData)

      if (!response.success) {
        throw new Error(response.msg || '上传失败')
      }

      return {
        ...response.data,
        folder_tag: fileItem.folderTag,
        original_filename: fileItem.file.name,
        relative_path: fileItem.relativePath
      }
    },

    // 发送上传请求
    uploadFileRequest(formData) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()

        xhr.open('POST', this.upload_url, true)
        xhr.setRequestHeader('Authorization', getToken())
        xhr.setRequestHeader('PTOKEN', this.$store.getters.projectId)

        xhr.onload = () => {
          if (xhr.status === 200) {
            try {
              const response = JSON.parse(xhr.responseText)
              resolve(response)
            } catch (error) {
              reject(new Error('响应解析失败'))
            }
          } else {
            reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`))
          }
        }

        xhr.onerror = () => {
          reject(new Error('网络错误'))
        }

        xhr.ontimeout = () => {
          reject(new Error('上传超时'))
        }

        xhr.timeout = 30000 // 30秒超时
        xhr.send(formData)
      })
    },

    // 发送文件夹上传完成事件给父组件
    emitFolderUploadComplete() {
      const result = {
        folderName: this.currentFolderUpload.folderName,
        totalFiles: this.currentFolderUpload.totalFiles,
        successFiles: this.currentFolderUpload.successFiles,
        failedFiles: this.currentFolderUpload.failedFiles,
        successCount: this.currentFolderUpload.successFiles.length,
        failedCount: this.currentFolderUpload.failedFiles.length
      }

      // 发送文件夹上传完成事件
      this.$emit('folder-upload-complete', result)

      // 同时为每个成功的文件发送insert事件（保持向后兼容）
      this.currentFolderUpload.successFiles.forEach(file => {
        this.$emit('insert', file)
        // 也添加到成功列表显示
        this.success_data.push(file)
      })

      this.isFolderUploading = false
      this.currentFolderUpload = null

      // 显示总结消息
      if (result.successCount > 0) {
        this.$notify({
          title: '文件夹上传完成',
          message: `文件夹 "${result.folderName}" 上传完成！成功: ${result.successCount}个，失败: ${result.failedCount}个`,
          type: result.failedCount === 0 ? 'success' : 'warning',
          duration: 5000
        })
      }
    },

    handleSuccess(response, file) {
      // 减少上传中的文件数量
      this.uploadingFiles--
      if (this.uploadingFiles <= 0) {
        this.isUploading = false
        this.uploadingFiles = 0
      }

      if (response.success) {
        this.$notify({
          title: '成功',
          message: `文件${file.name}上传成功`,
          type: 'success',
          duration: 2000
        })

        const uid = file.uid
        const objKeyArr = Object.keys(this.listObj)
        for (let i = 0; i < objKeyArr.length; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            this.listObj[objKeyArr[i]].url = response.data.url
            this.success_data.push(response.data)
            this.listObj[objKeyArr[i]].hasSuccess = true

            // 自动执行插入操作
            this.handleInsertFile(response.data)
            return
          }
        }
      } else {
        this.$notify({
          title: '失败',
          message: `文件${file.name}上传失败, ${response.msg}`,
          type: 'error',
          duration: 3000
        })
      }
    },

    // 文件移除方法
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0; i < objKeyArr.length; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },

    // 上传前检查
    beforeUpload(file) {
      const _self = this
      const fileName = file.uid
      this.listObj[fileName] = {}

      // 开始上传状态
      this.isUploading = true
      this.uploadingFiles++

      return new Promise((resolve) => {
        _self.listObj[fileName] = { hasSuccess: false, uid: file.uid }
        resolve(true)
      })
    },

    // 图片粘贴处理
    handlePaste(event) {
      const items = (event.clipboardData || event.originalEvent.clipboardData).items
      let hasImageFile = false
      let imageType = 'image/png' // 默认类型

      for (const index in items) {
        const item = items[index]
        if (item.kind === 'file' && item.type.startsWith('image/')) {
          hasImageFile = true
          imageType = item.type // 保存实际的图片类型

          // 阻止默认粘贴行为，避免图片被插入到contenteditable div中
          event.preventDefault()

          const blob = item.getAsFile()
          const reader = new FileReader()
          reader.onload = (e) => {
            this.pastedImage = e.target.result
            this.pastedImageType = imageType // 保存图片类型
            // 自动提交粘贴的图片
            this.submitImage()
          }
          reader.readAsDataURL(blob)
          break // 只处理第一个图片文件
        }
      }

      if (!hasImageFile) {
        this.$message.warning('请粘贴图片文件')
      }
    },

    // 粘贴图片提交
    submitImage() {
      if (!this.pastedImage) {
        this.$message.error('没有检测到粘贴的图片')
        return
      }

      // 开始上传状态
      this.isPasteUploading = true

      // 使用和文件上传一样的接口
      const uploadData = {
        file_data: this.pastedImage,
        directory_id: this.uploadData.directory_id || -1,
        acl_type: this.uploadData.acl_type || '7',
        project_id: this.uploadData.project_id,
        directory_name: this.uploadData.directory_name || ''
      }

      // 使用 XMLHttpRequest 发送 POST 请求到 /crm/api/crmfile/
      const xhr = new XMLHttpRequest()
      xhr.open('POST', this.upload_url, true)
      xhr.setRequestHeader('Authorization', getToken())
      xhr.setRequestHeader('PTOKEN', this.$store.getters.projectId)
      xhr.setRequestHeader('Content-Type', 'application/json')

      xhr.onload = () => {
        this.isPasteUploading = false

        if (xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText)
            if (response.success) {
              this.$message.success('图片上传成功')

              // 使用后端返回的完整数据
              const fileData = response.data
              this.success_data.push(fileData)

              // 自动执行插入操作
              this.handleInsertFile(fileData)
            } else {
              this.$message.error(`图片上传失败: ${response.msg}`)
            }
          } catch (error) {
            this.$message.error('响应解析失败')
            console.error('响应解析失败:', error)
          }
        } else {
          this.$message.error(`图片上传失败: HTTP ${xhr.status}`)
        }

        // 清空粘贴的图片
        this.pastedImage = ''
        this.pastedImageType = 'image/png'

        // 清空粘贴区域的内容
        if (this.$refs.pasteArea) {
          this.$refs.pasteArea.innerHTML = ''
        }
      }

      xhr.onerror = () => {
        this.isPasteUploading = false
        this.$message.error('网络错误')
        console.error('网络错误')

        // 清空粘贴的图片
        this.pastedImage = ''
        this.pastedImageType = 'image/png'
      }

      xhr.ontimeout = () => {
        this.isPasteUploading = false
        this.$message.error('上传超时')

        // 清空粘贴的图片
        this.pastedImage = ''
        this.pastedImageType = 'image/png'
      }

      xhr.timeout = 30000 // 30秒超时
      xhr.send(JSON.stringify(uploadData))
    },

    // 文件插入方法
    handleInsertFile(item) {
      this.$emit('insert', item)
    },

    // 清空上传结果
    clearResults() {
      this.success_data = []
      this.fileList = []
      this.listObj = {}
      this.pastedImage = ''
      this.pastedImageType = 'image/png'
      this.isPasteUploading = false
    },

    handleProgress(event, file) {
      // 上传进度处理
      console.log('上传进度:', Math.round(event.percent), '%')
    },

    handleError(error, file) {
      // 减少上传中的文件数量
      this.uploadingFiles--
      if (this.uploadingFiles <= 0) {
        this.isUploading = false
        this.uploadingFiles = 0
      }

      // 处理错误信息
      const errorMessage = error && error.message ? error.message : '网络错误或服务器异常'

      this.$notify({
        title: '上传失败',
        message: `文件${file.name}上传失败: ${errorMessage}`,
        type: 'error',
        duration: 3000
      })

      // 记录错误到控制台
      console.error('文件上传失败:', error, file)
    }
  }
}
</script>

<style lang="scss" scoped>
.quick-upload-container {
  width: 100%;
  position: relative;
  display: flex;
  justify-content: center;
}

// 收缩状态的小窗口样式
.collapsed-window {
  width: 160px;
  background: #e3f2fd;
  border: 1px solid #bbdefb;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

  &:hover {
    background: #bbdefb;
    border-color: #90caf9;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
  }

  .collapsed-content {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 6px 8px;
    color: #1565c0;
    font-size: 12px;
    font-weight: 500;

    i.el-icon-upload2 {
      font-size: 12px;
      margin-right: 4px;
      color: #1565c0;
    }

    .collapsed-text {
      margin-right: 4px;
    }

    .expand-icon {
      font-size: 12px;
      transition: transform 0.3s ease;
      color: #1565c0;
    }
  }

  &:hover .expand-icon {
    transform: translateY(1px);
  }

  // 紧凑模式样式
  &.compact-mode {
    width: 80px;
    background: #f8f9fa;
    border: 1px solid #e9ecef;

    &:hover {
      background: #e9ecef;
      border-color: #dee2e6;
    }

    .collapsed-content {
      padding: 4px 6px;
      font-size: 11px;

      i.el-icon-upload2 {
        font-size: 11px;
        margin-right: 3px;
      }

      .collapsed-text {
        margin-right: 3px;
      }

      .expand-icon {
        font-size: 10px;
      }
    }
  }

  // 仅图标模式样式
  &.icon-only {
    width: 32px;
    height: 32px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: 1px solid #667eea;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.3);

    &:hover {
      background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
      border-color: #5a67d8;
      transform: scale(1.1);
      box-shadow: 0 4px 8px rgba(102, 126, 234, 0.4);
    }

    .collapsed-content {
      padding: 0;
      font-size: 14px;

      i.el-icon-upload2 {
        font-size: 14px;
        margin: 0;
        color: #ffffff;
      }
    }

    &:hover .collapsed-content i.el-icon-upload2 {
      color: #ffffff;
    }
  }
}

// 展开状态的完整界面样式
.expanded-window {
  width: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  border: 1px solid #e3f2fd;
  margin-top: 10px;

  // 默认展开时不需要动画
  &.default-expanded {
    animation: none;
    margin-top: 0;
    box-shadow: none;
    border: 1px solid #e9ecef;
    border-radius: 4px;
  }

  &:not(.default-expanded) {
    animation: expandAnimation 0.3s ease-out;
  }
}

@keyframes expandAnimation {
  from {
    opacity: 0;
    transform: translateY(-10px) scale(0.98);
    max-height: 0;
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
    max-height: 400px;
  }
}

.upload-content {
  padding: 15px;
  background: #fafbfc;
  min-height: 150px;
  max-height: 40vh;
  overflow-y: auto;

  .default-expanded & {
    background: #fff;
    padding: 10px;
    min-height: 120px;
  }
}

.upload-layout {
  display: flex;
  gap: 15px;
  align-items: flex-start;
}

.upload-left {
  flex: 1;
  min-width: 0;
}

.upload-right {
  width: 280px;
  background: #fff;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}

.success-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f0f9ff;
  border-bottom: 1px solid #e0f2fe;

  .success-title {
    color: #0369a1;
    font-size: 12px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 4px;

    i {
      color: #059669;
      font-size: 12px;
    }
  }

  .clear-btn {
    color: #6b7280;
    padding: 2px;

    &:hover {
      color: #dc2626;
    }

    i {
      font-size: 12px;
    }
  }
}

.success-list {
  max-height: 200px;
  overflow-y: auto;

  .success-item {
    display: flex;
    align-items: center;
    padding: 6px 12px;
    border-bottom: 1px solid #f3f4f6;
    transition: background-color 0.2s;

    &:hover {
      background-color: #f8fafc;
    }

    &:last-child {
      border-bottom: none;
    }

    i.el-icon-document {
      color: #6b7280;
      font-size: 12px;
      margin-right: 6px;
      flex-shrink: 0;
    }

    .file-name {
      flex: 1;
      font-size: 11px;
      color: #374151;
      text-decoration: none;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-right: 6px;

      &:hover {
        color: #1565c0;
      }
    }

    .success-tag {
      background: #dcfce7;
      border-color: #bbf7d0;
      color: #166534;
      padding: 1px 4px;
      border-radius: 4px;
      flex-shrink: 0;

      i {
        font-size: 10px;
      }
    }
  }

  .more-files {
    padding: 6px 12px;
    text-align: center;
    font-size: 11px;
    color: #6b7280;
    background: #f9fafb;
    border-top: 1px solid #f3f4f6;
  }
}

.upload-tabs {
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  overflow: hidden;

  :deep(.el-tabs__header) {
    margin: 0;
    background: #f8f9fa;
    border-bottom: 1px solid #e9ecef;
  }

  :deep(.el-tabs__content) {
    padding: 12px;
  }

  :deep(.el-tabs__item) {
    padding: 0 15px;
    height: 36px;
    line-height: 36px;
    font-weight: 500;
    font-size: 13px;

    &.is-active {
      color: #1565c0;
      background: #fff;
    }
  }

  .upload-area {
    width: 100%;

    :deep(.el-upload-dragger) {
      width: 100%;
      height: 120px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      border: 2px dashed #d1ecf1;
      background: #f8fdff;
      transition: all 0.3s ease;
      padding: 15px;

      &:hover {
        border-color: #1565c0;
        background: #e3f2fd;
      }
    }

    // 上传中状态样式
    &.uploading :deep(.el-upload-dragger) {
      border-color: #52c41a;
      background: #f6ffed;
      animation: uploadingPulse 2s infinite;

      &:hover {
        border-color: #52c41a;
        background: #f6ffed;
      }
    }

    .upload-normal {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      text-align: center;

      i {
        font-size: 24px;
        color: #1565c0;
        margin-bottom: 8px;
      }

      .el-upload__text {
        color: #495057;
        font-size: 13px;
        line-height: 1.4;
        margin-bottom: 6px;
        word-wrap: break-word;
        word-break: break-word;
        max-width: 100%;
        padding: 0 10px;
        display: block;

        em {
          color: #1565c0;
          font-style: normal;
        }
      }

      .el-upload__tip {
        color: #6c757d;
        font-size: 11px;
        line-height: 1.3;
        margin-top: 2px;
        word-wrap: break-word;
        max-width: 100%;
        padding: 0 10px;
      }
    }

    .upload-progress {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .uploading-icon {
        font-size: 24px;
        color: #52c41a;
        margin-bottom: 6px;
        animation: spin 1s linear infinite;
      }

      .uploading-text {
        color: #52c41a;
        font-size: 12px;
        font-weight: 500;
        margin-bottom: 2px;
      }

      .uploading-count {
        color: #73d13d;
        font-size: 11px;
      }
    }
  }
}

.paste-tab-content {
  display: flex;
  gap: 8px;
  align-items: flex-start;
  margin-bottom: 10px;
}

.paste-area {
  flex: 1;
  border: 2px dashed #d1ecf1;
  padding: 12px;
  min-height: 120px;
  background: #f8fdff;
  border-radius: 4px;
  transition: all 0.3s;
  font-size: 12px;
  color: #6c757d;
  display: flex;
  align-items: center;
  justify-content: center;

  &:focus {
    outline: none;
    border-color: #1565c0;
    background: #e3f2fd;
    box-shadow: 0 0 0 2px rgba(21, 101, 192, 0.1);
  }

  &::placeholder {
    color: #adb5bd;
  }

  .paste-hint {
    text-align: center;
    width: 100%;

    i {
      font-size: 24px;
      color: #1565c0;
      margin-bottom: 6px;
      display: block;
    }

    p {
      margin: 0;
      line-height: 1.4;

      &:first-of-type {
        font-size: 13px;
        color: #495057;
        margin-bottom: 4px;
      }

      &.paste-tip {
        font-size: 10px;
        color: #999;
        margin-top: 1px;
      }
    }
  }

  .paste-uploading {
    text-align: center;
    width: 100%;

    i {
      font-size: 24px;
      color: #52c41a;
      margin-bottom: 6px;
      display: block;
      animation: spin 1s linear infinite;
    }

    p {
      margin: 0;
      line-height: 1.4;
      color: #52c41a;
      font-weight: 500;
      font-size: 13px;
    }
  }

  &.uploading {
    border-color: #52c41a;
    background: #f6ffed;

    &:focus {
      border-color: #52c41a;
      background: #f6ffed;
    }
  }
}

.paste-options {
  width: 80px;

  .access-select {
    width: 100%;
  }
}

.submit-image-btn {
  width: 100%;
  background: #1565c0;
  border-color: #1565c0;

  &:hover {
    background: #0d47a1;
    border-color: #0d47a1;
  }
}

// 响应式调整
@media screen and (max-width: 768px) {
  .upload-layout {
    flex-direction: column;
  }

  .upload-right {
    width: 100%;
    order: -1;
    margin-bottom: 15px;
  }

  .paste-tab-content {
    flex-direction: column;
  }

  .paste-options {
    width: 100%;
  }

  .upload-tabs {
    :deep(.el-upload-dragger) {
      height: 140px;
      padding: 20px 10px;
    }

    .upload-normal {
      .el-upload__text {
        font-size: 12px;
        padding: 0 5px;
      }

      .el-upload__tip {
        font-size: 10px;
        padding: 0 5px;
      }
    }
  }
}

// 收缩提示条
.collapse-hint {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4px;
  background: #e3f2fd;
  border-bottom: 1px solid #bbdefb;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #1565c0;
  font-size: 11px;

  &:hover {
    background: #bbdefb;
  }

  i {
    margin-right: 3px;
    font-size: 12px;
  }

  span {
    font-weight: 500;
  }
}

@keyframes uploadingPulse {
  0% {
    box-shadow: 0 0 0 0 rgba(82, 196, 26, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(82, 196, 26, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(82, 196, 26, 0);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

// 文件夹上传样式
.folder-upload-progress {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  i.el-icon-folder {
    font-size: 24px;
    color: #1565c0;
    margin-bottom: 6px;
  }

  .folder-upload-text {
    color: #1565c0;
    font-size: 12px;
    font-weight: 500;
    margin-bottom: 2px;
  }

  .folder-upload-count {
    color: #3f51b5;
    font-size: 11px;
    margin-bottom: 5px;
  }
}

// 文件夹确认对话框样式
.folder-confirm-content {
  p {
    margin: 8px 0;
    font-size: 14px;
    color: #333;

    strong {
      color: #1565c0;
    }
  }

  .folder-tag-hint {
    font-size: 12px;
    color: #666;
    background: #f5f5f5;
    padding: 8px;
    border-radius: 4px;
    border-left: 3px solid #1565c0;
  }
}
</style>
